package com.qianxx.base.loading;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.qianxx.draw.R;
import com.qianxx.base.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;
/**
 * 
 * @author you.y
 */
public class LoadingView extends LinearLayout {

	private Activity mContext;
	private List<View> viewList = new ArrayList<View>();
	private int index;
	private long startTime; // 开始loading的时间戳

	public LoadingView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mContext = (Activity) context;
		initView();
	}

	private void initView() {
		View layout = LayoutInflater.from(mContext).inflate(
				R.layout.base_lay_loading_view, null);
		viewList.clear();
		int[] resId = new int[] { R.id.loadingItem1, R.id.loadingItem2,
				R.id.loadingItem3 };
		for (int i = 0; i < resId.length; i++) {
			View item = layout.findViewById(resId[i]);
			viewList.add(item);
		}
		setDisplay();
		addView(layout); // 添加到LoadingView中
	}

	private void setDisplay() {
		if (viewList.size() != 3) {
			LogUtil.w("LoadingView --- viewList.size()必须为3");
			return;
		}
		if (index >= 3) {
			LogUtil.e("LoadingView --- index必须小于3");
			return;
		}
		mContext.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// 设置显示
				for (int i = 0; i < viewList.size(); i++) {
					View item = viewList.get(i);
					if (i == index) {
						item.setSelected(true);
					} else {
						item.setSelected(false);
					}
				}
			}
		});

	}

	// 开启loading动画
	public void startLoading() {
		if (startTime != 0) {
			return;
		}
		startTime = System.currentTimeMillis();
		autoRepeat();
	}

	private void autoRepeat() {
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				if (startTime == 0) {
					return;
				}
				index++;
				index %= 3;
				setDisplay();
				autoRepeat();
			}
		}, 400);
	}

	// 关闭loading动画
	public void stopLoading() {
		startTime = 0;
		index = 0;
		setDisplay();
	}

}
